// 2013-7-28下午12:40:10  net.betou.trade.admin.action.IntermediateProviderAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.DataConvertUtils;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.RequestUtils;
import net.betou.common.web.springmvc.RealPathResolver;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.AgentAndAdminsExt;
import net.betou.trade.entity.main.Picture;
import net.betou.trade.main.manager.PictureMng;
import net.betou.trade.main.manager.agencyorproxy.AgencyMng;
import net.betou.trade.main.manager.role.AgencyRoleMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 机构管理Action
 * @author 叶装装
 */
@Controller
public class AgentAct extends ActionSupport< AgentAndAdmins >{

	private static final Logger log = LoggerFactory.getLogger( AgentAct.class );
	
	private static final String DIRECTORY = "agent";
	
	@RequestMapping( "/agent/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		Pagination pagination = mng.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
		
		model.addAttribute( "admin", admin );
		
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		return getListPage( );
	}
	
	/**
	 * 添加机构的时候, 要有选择的, 比如添加机构的时候, 不管是管理员还是非管理员,他的角色就是机构
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping( "/agent/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		model.addAttribute( "admin", admin );
		return getAddPage( );
	}
	
	@RequestMapping( "/agent/o_save.jspx" )
	public String o_save( AgentAndAdmins bean, AgentAndAdminsExt ext,  String [] pic,  HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		String ip = RequestUtils.getIpAddr( request );
		
		bean = mng.save( admin, ip, bean, ext, pic );
		
	//	logMng.operating( 0, request, Messages.LOG_INTERMEDIA, "id=" + bean.getId( ) + ",name=" + bean.getIntermediaName( ) );
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping ( "/agent/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean =  mng.findById( id ); //manager.findById( id );
		
		model.addAttribute( "bean", bean );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		model.addAttribute( "admin", admin );
		
		AgentAndAdmins deepZeroAgency = null;
		boolean system = admin.getSystem( );
		
		if( system ){
			if( bean.getDeep( ) == 0 ){ // 是顶级角色，所以这个就为bean
				deepZeroAgency = bean;
			}else{
				deepZeroAgency = mng.findById( DataConvertUtils.getInt( StringUtils.split( bean.getTopIntermedia( ), ",")[ 0 ] ) );
			}
		}else{
			if( admin.getDeep( ) > 0 ){  // 表示不是顶级机构，就要查询出顶级机构的角色
				admin = mng.findById( DataConvertUtils.getInt( StringUtils.split( bean.getTopIntermedia( ), ",")[ 0 ] ) );
			}
		}
		
		model.addAttribute( "roleList", roleMng.list( admin, deepZeroAgency ) );
		
		return getUpdatePage( );
	}
	
	/**
	 * @return
	 */
	@RequestMapping ( "/agent/o_update.jspx" )
	public String o_update( Boolean disabled, Integer id, String password, String mobile, String intermediaName, String email, Integer [ ] roleIds,  String [] pic, Integer[] picIds, AgentAndAdminsExt ext, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOUpdate( admin, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findAgency( id ); // 已经经过验证了
	
		bean = mng.update( disabled, password, email, mobile, intermediaName, bean, ext, roleIds, pic, picIds );
		
		logMng.operating( 1, request, Messages.LOG_INTERMEDIA, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/agent/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateDelete( ids, admin, response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		AgentAndAdmins [ ] beans = mng.deleteByIds( ids );

		for ( AgentAndAdmins bean : beans ){
			log.info( "delete Admin id={}", bean.getId( ) );
			
			logMng.operating( 2, request, Messages.LOG_INTERMEDIA, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
	}
	
	
	@RequestMapping( "/agent/o_delete_img.jspx" )
	public void o_delete( Integer id, HttpServletResponse response, HttpServletRequest request ){
		
		ResponseUtil util = ResponseUtil.create( response );

		Picture p = picMng.findById( id );
		
		if( p == null ){
			util.addErrorResponse( Messages.DATA_NOT_EXIST );
			util.renderJson( );
			return;
		}
		
		picMng.deleteById( id );
		
		String path = p.getPath( );
		String deletePath = realPath.get( path );
		
		File file = new File( deletePath );
		
		file.delete( );
		
		util.addSuccessResponse( Messages.DATA_DELETE_SUCCESS );

		util.renderJson( );
		return;
	}
	
	@RequestMapping( "/agent/v_agency_tree.jspx" )
	public String v_agency_tree( HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		return DIRECTORY + TREE_AGENCY_VIEW;
	}
	
	@RequestMapping( "/agent/v_account_tree.jspx" )
	public String v_account_tree( HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		return DIRECTORY + TREE_ACCOUNT_VIEW;
	}
	
	/**
	 * 如果是系统管理员，就显示出所有的机构
	 * 如果不是系统管理员，就显示自己下面的所有的机构, 这个显示的方式为. 要把自己的加进去
	 * @return
	 */
	@RequestMapping( "/agent/o_agency_tree.jspx" )
	public String o_agency_tree( String root, HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		// 返回到tree页面
		
		boolean isRoot = isRoot( root, model );
		
		List< AgentAndAdmins > list;
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		if( isRoot ){
			list = mng.listAgencyToTreeForParent( admin );
			list.add( admin ); // 不考虑是否为系统管理员
		}else{
			list = mng.listAgencyToTreeForChild( DataConvertUtils.getInt( root ) );
		}

		setModel( model, admin, list, response );
		
		return DIRECTORY + TREE_AGENCY;
	}
	
	@RequestMapping( "/agent/o_account_tree.jspx" )
	public String o_account_tree( String root, HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		// 返回到tree页面
		
		boolean isRoot = isRoot( root, model );
		
		List< AgentAndAdmins > list;
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		if( isRoot ){
			list = mng.listAccountToTreeForParent( admin );
			list.add( admin ); // 不考虑是否为系统管理员
		}else{
			list = mng.listAccountToTreeForChild( DataConvertUtils.getInt( root ) );
		}

		setModel( model, admin, list, response );
		
		return DIRECTORY + TREE_ACCOUNT;
	}
	
	private void setModel( ModelMap model, AgentAndAdmins admin, List< AgentAndAdmins > list, HttpServletResponse response ){
		model.addAttribute( "list", list );
		model.addAttribute( "admin", admin );
		response.setHeader( "Cache-Control", "no-cache" );
		response.setContentType( "text/json;charset=UTF-8" );
	}
	
	private boolean isRoot( String root, ModelMap model ){
		boolean isRoot;
		if( StringUtils.isBlank( root ) || "source".equals( root ) ){
			isRoot = true;
		}else{
			isRoot = false;
		}
		
		model.addAttribute( "isRoot", isRoot );
		return isRoot;
		
	}
	
	private ResponseUtil validateDelete( Integer [ ] ids,AgentAndAdmins admin, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			AgentAndAdmins bean = mng.findBySelf( admin, id ); 
			if( bean == null ){
				util.addErrorResponse( admin.getSystem( ) ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}
	
	
	private WebErrors validateOUpdate( AgentAndAdmins admin, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins bean = mng.findBySelf( admin, id );
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		return errors;
		
	}
	/**
	 * 此处的判断为, 查找居间商,如果不是,则返回错误消息..
	 * 避免恶意ID传入信息被修改
	 * @param request
	 * @param id
	 * @return
	 */
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins admin = mng.findAgency( id );
		
		if( admin == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( AgentAndAdmins bean ){
		WebErrors errors = WebErrors.create( );
		
		return errors;
	}
	
	private static final String TREE_AGENCY_VIEW = "/tree_agency_view";
	private static final String TREE_AGENCY = "/tree_agency";
	private static final String TREE_ACCOUNT_VIEW = "/tree_account_view";
	private static final String TREE_ACCOUNT = "/tree_account";
	
	@Autowired
	private AgencyMng mng;
	
	@Autowired
	private AgencyRoleMng roleMng;

	@Autowired
	private PictureMng picMng;
	
	@Autowired
	private RealPathResolver realPath;

	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}
}
